<template>
  <div>
    <el-dialog
        title="查看租期"
        :visible.sync="dialogVisible"
        width="1400px"
    >
      <!--      <el-table :data="tableData_1" border style="margin-bottom:10px">-->
      <!--        <el-table-column align="center" label="预授权余款">-->
      <!--          <template slot-scope="scope">-->
      <!--            <span>￥{{ Number(scope.row.rent).toFixed(2) }}</span>-->
      <!--          </template>-->
      <!--        </el-table-column>-->
      <!--        <el-table-column align="center" label="已扣款额">-->
      <!--          <template slot-scope="scope">-->
      <!--            <span>￥{{ Number(scope.row.rent_close).toFixed(2) }}</span>-->
      <!--          </template>-->
      <!--        </el-table-column>-->
      <!--        <el-table-column align="center" label="剩余可扣款额">-->
      <!--          <template slot-scope="scope">-->
      <!--            <span>￥{{ Number(scope.row.rent_other).toFixed(2) }}</span>-->
      <!--          </template>-->
      <!--        </el-table-column>-->

      <!--        <el-table-column fixed="right" align="center" label="操作" width="280">-->
      <!--          <template slot-scope="scope">-->
      <!--            <el-button-->
      <!--              v-if="-->
      <!--                scope.row.order_status != 1 &&-->
      <!--                  $hasMethod('#withhold')-->
      <!--              "-->
      <!--              type="warning"-->
      <!--              size="mini"-->
      <!--              @click="dialogVisibleRent_yu = true"-->
      <!--            >发起代扣</el-button>-->
      <!--          </template>-->
      <!--        </el-table-column>-->
      <!--      </el-table>-->
      <youzupermiss v-if="status == '10'" style="margin-bottom:10px;text-align:right;">
        <el-button @click="updateWhich" type="primary">修改租期</el-button>
      </youzupermiss>
      <el-table
          :data="tableData"
          border
      >
        <el-table-column
            label="订单"
            prop="trade_no"
            width="120"
        />
        <el-table-column
            align="center"
            label="期数"
            width="80"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.which_period }}/{{ scope.row.month_total }}</span>
          </template>
        </el-table-column>
        <el-table-column
            align="center"
            label="租期"
            width="120"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.begin_time }} 至 {{ scope.row.end_time }}</span>
          </template>
        </el-table-column>
        <el-table-column
            align="center"
            label="租金"
            width="120"
        >
          <template slot-scope="scope">
            <span>￥{{ scope.row.rent }}</span>
          </template>
        </el-table-column>
        <el-table-column
            align="center"
            label="状态"
            width="100"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.status==0||scope.row.status==4?'':scope.row.status==2 ? 'danger' : 'success'">{{ scope.row.status==1?'已支付':scope.row.status==2?'已退款':scope.row.status==3?'已买断':scope.row.status==4?'已逾期':scope.row.status==5?'线下支付':'未支付' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
            align="center"
            label="支付时间"
            prop="pay_time"
            width="100"
        />
        <el-table-column
            align="center"
            label="预计扣款日"
            prop="begin_time"
            width="100"
        />
        <el-table-column
            align="center"
            label="流水号"
            width="100"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.pay_time?scope.row.alipay_trade_no:'' }}</span>
          </template>
        </el-table-column>
        <el-table-column
            align="center"
            label="自动扣款功能"
        >
          <template slot-scope="scope">
            <el-switch
                v-model="scope.row.withhold_status"
                active-color="#2993FF"
                inactive-color="#666666"
                :active-value="1"
                :inactive-value="2"
                @change="switchChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="280">
          <template slot-scope="scope">
            <el-button
                type="primary"
                size="mini"
                @click="viewLog(scope.row)"
            >查看记录</el-button>
            <el-button class="buttonSize"
                       v-if="yfbSign === 1 && scope.row.fq_withhold == 1 && (scope.row.status === 0 || scope.row.status == 2)"
                       type="warning"
                       size="mini"
                       @click="withholdItem(scope.row)"
            >发起代扣</el-button>
            <el-button
                v-if="scope.row.status == 0 || scope.row.status == 4"
                type="primary"
                size="mini"
                @click="lookQrcode(scope.row)"
            >生成支付码</el-button>
            <el-button
                v-if="scope.row.status == 1"
                class="buttonSize"
                type="danger"
                size="mini"
                @click="rentRefund(scope.row)"
            >退款</el-button>
            <!--            <el-button-->
            <!--              v-if="scope.row.is_withhold==1&&scope.row.pay_type==1&&$hasMethod('#withhold')"-->
            <!--              type="warning"-->
            <!--              size="mini"-->
            <!--              @click="openChangeRent(scope.row)"-->
            <!--            >修改租金</el-button>-->
            <!-- <el-button
              v-if="scope.row.is_withhold==1&&scope.row.pay_type!=1&&$hasMethod('#withhold')"
              type="warning"
              size="mini"
              @click="clickXZ(scope.row)"
            >销账</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <div
          slot="footer"
          class="dialog-footer"
      >
        <el-button
            type="primary"
            @click="dialogVisible=false"
        >关闭</el-button>
      </div>
      <deduct-log
          ref="deductLog"
          :order-no="selectedItem.trade_no"
          :lease-id="selectedItem.id"
      />
    </el-dialog>
    <el-dialog
        title="修改租金"
        :visible.sync="dialogVisibleRent"
        width="300px"
    >
      <el-form
          :model="selectedItem"
          label-width="40px"
      >
        <el-form-item label="租金">
          <el-input
              v-model="selectedItem.rent"
              type="number"
              style="width:200px"
              placeholder="请输入租金"
          />
        </el-form-item>
      </el-form>
      <div
          slot="footer"
          class="dialog-footer"
      >
        <el-button
            size="small"
            @click="dialogVisibleRent = false"
        >取 消</el-button>
        <el-button
            size="small"
            type="primary"
            @click="changeRent"
        >确 定</el-button>
      </div></el-dialog>
    <el-dialog
        title="代扣金额"
        :visible.sync="dialogVisibleRent_yu"
        width="300px"
    >
      <el-form
          :model="selectedItem"
          label-width="40px"
      >
        <el-form-item label="金额">
          <el-input
              v-model="rent_yu"
              type="number"
              step="0.01"
              style="width:200px"
              placeholder="请输入金额"
          />
        </el-form-item>
      </el-form>
      <div
          slot="footer"
          class="dialog-footer"
      >
        <el-button
            size="small"
            @click="dialogVisibleRent_yu = false"
        >取 消</el-button>
        <el-button
            size="small"
            type="primary"
            @click="withholdItem_1"
        >确 定</el-button>
      </div></el-dialog>
    <el-dialog
        title="查看二维码"
        :visible.sync="dialogVisibleQrcode"
        width="400px"
    >
      <div class="canvasBox">
        <canvas width="164" height="164" id="canvas"></canvas>
      </div>
    </el-dialog>
    <el-dialog
        title="支付金额"
        :visible.sync="dialogVisibleQrcodePrice"
        width="400px"
    >
      <el-input v-model="totalAmount" placeholder="请输入金额"></el-input>
      <div
          slot="footer"
          class="dialog-footer"
      >
        <el-button
            size="small"
            @click="dialogVisibleQrcodePrice = false"
        >取 消</el-button>
        <el-button
            size="small"
            type="primary"
            @click="showQrcode"
        >确 定</el-button>
      </div>
    </el-dialog>
    <updateLease @init="getLeaseTS" ref="updateLease"></updateLease>
  </div>
</template>

<script>
import { getLease, changeRent, finishPay, paySigning,rentRefund } from '@/api/order'
import { manualWithholding, withholdSwitch, manualWithholding_XZ, manualWithholding_1 } from '@/api/finance'
import deductLog from './deductLog'
import qrcode from 'qrcode'
import updateLease from './updateLease.vue'
export default {
  components: { deductLog,updateLease },
  props: ['orderId'],
  data() {
    return {
      dialogVisible: false,
      dialogVisibleRent: false,
      dialogVisibleRent_yu: false,
      totalAmount:"",
      dialogVisibleQrcode:false,
      dialogVisibleQrcodePrice:false,
      tableData: [],
      selectedItem: {},
      status:-1,
      tableData_1: [{
        orderId: 0,
        rent: 0,
        rent_close: 0,
        rent_other: 0
      }],
      yfbSign:-1,
      interval: null,
      rent_yu: 0
    }
  },
  watch: {
    dialogVisible(val) {
      if (val) {
        this.getLeaseTS()
      }
    },
    dialogVisibleQrcode(val) {
      if (!val) {
        clearInterval(this.interval)
      }
    }
  },
  methods: {
    init(data){
      this.yfbSign = data.yfbSign;
      this.status = data.status;
    },
    updateWhich(){
      this.$refs.updateLease.open(this.orderId);
    },
    rentRefund(row) {
      const that = this
      this.$confirm('您确定要退款吗？', '发起退款', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
          .then(() => {
            rentRefund({
              orderId: row.order_id,
              which_period: row.which_period
            }).then((res) => {
              setTimeout(() => {
                that.getLeaseTS()
                // that.getList(true)
                that.$parent.getList(true)
              }, 1000)
            })
          })
          .catch(() => {})
    },
    lookQrcode(row){
      this.totalAmount = "";
      // this.$router.push({ name: 'alipay',query:{order_id:row.order_id,which_id:row.id} });
      this.dialogVisibleQrcodePrice = true;
      this.handleRow = {...row};
    },
    showQrcode() {
      if (this.totalAmount.trim() == '' || this.totalAmount == 0) {
        this.$message.error('请输入金额')
        return
      }
      if (this.totalAmount < 0) {
        this.$message.error('请输入正确的金额')
        return
      }
      const row = this.handleRow
      this.dialogVisibleQrcodePrice = false
      this.dialogVisibleQrcode = true
      this.$nextTick(() => {
        this.interval = setInterval(() => {
          finishPay(row.id).then((res) => {
            if (res == '支付成功') {
              clearInterval(this.interval)
              this.dialogVisibleQrcode = false
              this.$message.success('支付成功')
              this.getLeaseTS()
            }
          })
        }, 1000)
        const canvas = document.getElementById('canvas')
        qrcode.toCanvas(canvas, window.location.origin + '/alipay?order_id=' + row.order_id + '&which_id=' + row.id + '&totalAmount=' + this.totalAmount, function(error) {
          if (error) console.error(error)
          console.log('success!')
        })
      })
    },
    clickXZ(row) {
      const that = this
      this.$confirm('您确定要销帐吗？', '发起代扣', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
          .then(() => {
            manualWithholding_XZ({
              orderId: row.order_id,
              leaseId: row.id
            }).then((res) => {
              setTimeout(() => {
                that.getLeaseTS()
                that.$parent.getList(true)
              }, 1000)
            })
          })
          .catch(() => {})
    },
    switchChange(row) {
      withholdSwitch({
        orderId: row.order_id,
        leaseId: row.id,
        withholdStatus: row.withhold_status
      }).then(res => {
        this.$parent.getList(true)
      })
    },
    viewLog(row) {
      this.selectedItem = { ...row }
      this.$refs.deductLog.dialogVisible = true
    },
    getLeaseTS() {
      getLease(this.orderId).then(res => {
        console.log(res);
        this.tableData = res || []
        this.tableData.forEach(data => {
          this.tableData_1[0].orderId = data.order_id
          this.tableData_1[0].rent = data.foregift_deduct - data.rent_total
          this.tableData_1[0].rent_close = data.rent_yu
          this.tableData_1[0].rent_other = this.tableData_1[0].rent - data.rent_yu
        })
      })
    },
    openChangeRent(row) {
      this.dialogVisibleRent = true
      this.selectedItem = { ...row }
    },
    changeRent() {
      const that = this
      changeRent({ 'order_id': this.orderId, 'which_period': this.selectedItem.which_period, 'rent': this.selectedItem.rent }).then(res => {
        this.dialogVisibleRent = false
        setTimeout(() => {
          that.getLeaseTS()
          that.$parent.getList(true)
        }, 1000)
      })
    },
    withholdItem(row) {
      console.log('row2', row)
      const that = this
      this.$confirm('您确定要发起代扣吗？', '发起代扣', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        // const that1 = that
        paySigning({
          order_id: row.order_id,
          leaseId: row.id,
          payType: 1
        }).then((res) => {
          setTimeout(() => {
            that.getLeaseTS()
            // that.getList(true)
            that.$parent.getList(true)
          }, 1000)
        })
      }).catch(() => { })
    },
    withholdItem_1() { // 余款代扣
      const that = this
      this.$confirm('您确定要发起代扣吗？', '发起代扣', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
          .then(() => {
            that.dialogVisibleRent_yu = false
            manualWithholding_1({
              orderId: that.tableData_1[0].orderId,
              leaseId: that.tableData_1[0].id,
              rent_yu: that.rent_yu
            }).then((res) => {
              setTimeout(() => {
                that.dialogVisible = false
                that.getLeaseTS()
                that.getList(true)
              }, 1000)
            })
          })
          .catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/.el-dialog__body {
  max-height: 650px;
  overflow: auto;
}
.canvasBox{
  width: 180px;
  margin:0 auto;
}
</style>
